<template>
  <viDialog
    :yearShow="true"
    :deptShow="true"
    :visibility.sync="visibility"
    :title="title"
    unit="万元"
    :deptList="deptList"
    :projectShow="true"
    @changeDept="changeDept"
    @changeYear="changeYear"
    @changeProject="changeProject"
  >
    <div class="content-dialog-body">
      <div class="left banner">
        <div class="header">
          <label>年度</label>
          <span>单位：万元</span>
        </div>
        <div ref="chart1" class="chart"></div>
        <!-- <viBar
          ref="reference3"
          :configurationInformation="configurationInformation"
        /> -->
      </div>
      <div class="right banner">
        <div class="header">
          <label>累计</label>
          <span>单位：万元</span>
        </div>
        <div ref="chart2" class="chart"></div>
        <!-- <viBar
          ref="reference4"
          :configurationInformation="configurationInformation"
        /> -->
      </div>
    </div>
  </viDialog>
</template>

<script>
import { viDialog, viLine, viBar } from "@/components/visualization/index";
import request from "@/utils/request";
import Qs from "qs";
import echarts from "echarts";

export default {
  name: "vi-popup-profit",
  components: {
    viDialog,
    viLine,
    viBar,
  },
  props: {
    monthList: {
      default: [],
    },
    deptList: {
      default: () => [],
    },
  },
  data() {
    return {
      flag: 1,
      visibility: false,

      infos1: {
        showHeader: true,
      },
      infos2: {
        showHeader: true,
      },
      configurationInformation: {
        colors: {
          default: "#F3684B",
          active: "#1890FF",
        },
        barwidth: "24",
        title: {
          name: "",
          unit: "",
        },
        radioList: {
          radio: "",
          list: [],
        },
        showHeader: true,
      },
      deptId: -1,
      year: null,
      title: "",
      projectId: null,
    };
  },
  created() {
    this.gettimes();
  },
  methods: {
    changeProject(val) {
      this.projectId = val;
      this.getData1();
      this.getData2();
    },
    gettimes() {
      const time = new Date();
      const year = time.getFullYear();
      const month = time.getMonth() + 1;
      const day = time.getDate();
      this.year = `${year}`;
    },
    isNumber(val) {
      var regPos = /^\d+(\.\d+)?$/; //非负浮点数
      var regNeg =
        /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
      if (regPos.test(val) || regNeg.test(val)) {
        return true;
      } else {
        return false;
      }
    },
    changeDept(val) {
      this.deptId = val;
      this.getData1();
      this.getData2();
    },
    changeYear(val) {
      this.year = val;
      this.getData1();
      this.getData2();
    },
    getData1() {
      request({
        url: "/system/screen/monthInOut",
        method: "post",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        data: Qs.stringify({
          deptId: this.deptId,
          year: this.year,
          projectId: this.projectId,
        }),
      }).then((res) => {
        const x = [];
        const y1 = [];
        const y2 = [];
        for (let i = 0; i < 12; i++) {
          x.push(`${i + 1}月`);
        }
        for (const i in res.data) {
          const data = res.data[i].split("|");
          console.log(this.isNumber(Number(data[0])), data[0]);
          if (!this.isNumber(data[0])) {
            data[0] = 0;
          }
          if (!this.isNumber(data[1])) {
            data[1] = 0;
          }
          y1.push((Number(data[0]) / 10000).toFixed(4) || 0);
          y2.push((Number(data[1]) / 10000).toFixed(4) || 0);
        }
        this.init1(y1, y2, x);
      });
    },
    getData2() {
      request({
        url: "/system/screen/yearInOut",
        method: "post",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        data: Qs.stringify({
          deptId: this.deptId,
          year: this.year,
          projectId: this.projectId,
        }),
      }).then((res) => {
        const x = [];
        const y1 = [];
        const y2 = [];
        for (const i in res.data) {
          x.push(i);
          const data = res.data[i].split("|");
          y1.push((Number(data[0]) / 10000).toFixed(4) || 0);
          y2.push((Number(data[1]) / 10000).toFixed(4) || 0);
        }
        this.init2(y1, y2, x);
      });
    },
    init1(yData1, yData2, xData) {
      const chart = echarts.init(this.$refs.chart1);
      // chart.clear(); //每次绘制清除一次画布
      // this.echartInit = chart;
      const option = {
        tooltip: {
          trigger: "axis",
        },
        // legend: {
        //   data: ["开票", "收款"],
        //   x: "top",
        //   y: "left",
        //   padding: [10, 0, 0, 16],
        //   textStyle: {
        //     fontSize: 14,
        //     color: "rgba(0,0,0,.48)",
        //   },
        //   icon: "circle",
        //   itemWidth: 12,
        //   itemHeight: 12,
        //   itemGap: 12,
        // },
        grid: {
          top: "20",
          left: "0",
          right: "20",
          bottom: "0",
          containLabel: true,
        },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            let time = `${new Date().getFullYear()}年${params[0].axisValue}`;
            if (params[0].axisValue.length > 3) {
              time = `${params[0].axisValue}年`;
            }
            const tip1 = `${params[0].marker}收入:${params[0].value}万元`;
            const tip2 = `${params[1].marker}支出:${params[1].value}万元`;
            return `${time}</br>${tip1}</br>${tip2}`;
          },
        },
        xAxis: {
          type: "category",
          splitLine: {
            show: false,
          },
          axisLabel: {
            show: true,
            textStyle: {
              // 数值样式
              color: "rgba(68,82,121,.48)",
              fontSize: 12,
            },
          },
          axisLine: {
            lineStyle: {
              // 设置轴颜色
              color: "rgba(0,0,0,.12)",
            },
          },
          axisTick: {
            show: false,
          },
          data: xData,
        },
        yAxis: {
          type: "value",
          axisTick: {
            show: false,
          },
          // show: false,
          //网格样式
          splitLine: {
            show: true,
            lineStyle: {
              color: ["rgba(0,0,0,.04)"],
              width: 1,
              type: "solid",
            },
          },
          axisLine: {
            show: false,
            lineStyle: {
              // 设置轴颜色
              color: "rgba(0,0,0,.48)",
            },
          },
        },
        series: [
          {
            name: "收入",
            type: "bar",
            symbol: "circle",
            color: "rgba(31, 197, 87, 1)",
            data: yData1,
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2, //设置线条粗细
                },
              },
            },
          },
          {
            name: "支出",
            type: "bar",
            symbol: "circle",
            color: "rgba(243, 104, 75, 1)",
            data: yData2,
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2, //设置线条粗细
                },
              },
            },
          },
        ],
      };
      chart.setOption(option);
      const resize = window.addEventListener("resize", () => {
        this.$nextTick(() => {
          setTimeout(() => {
            chart.resize();
          }, 500);
        });
      });
      this.$once("hook:beforeDestroy", () => {
        window.removeEventListener("resize", resize);
      });
    },
    init2(yData1, yData2, xData) {
      const chart = echarts.init(this.$refs.chart2);
      // chart.clear(); //每次绘制清除一次画布
      // this.echartInit = chart;
      const option = {
        tooltip: {
          trigger: "axis",
        },
        // legend: {
        //   data: ["开票", "收款"],
        //   x: "top",
        //   y: "left",
        //   padding: [10, 0, 0, 16],
        //   textStyle: {
        //     fontSize: 14,
        //     color: "rgba(0,0,0,.48)",
        //   },
        //   icon: "circle",
        //   itemWidth: 12,
        //   itemHeight: 12,
        //   itemGap: 12,
        // },
        grid: {
          top: "20",
          left: "0",
          right: "20",
          bottom: "0",
          containLabel: true,
        },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            let time = `${new Date().getFullYear()}年${params[0].axisValue}`;
            if (params[0].axisValue.length > 3) {
              time = `${params[0].axisValue}年`;
            }
            const tip1 = `${params[0].marker}收入:${params[0].value}万元`;
            const tip2 = `${params[1].marker}支出:${params[1].value}万元`;
            return `${time}</br>${tip1}</br>${tip2}`;
          },
        },
        xAxis: {
          type: "category",
          splitLine: {
            show: false,
          },
          axisLabel: {
            show: true,
            textStyle: {
              // 数值样式
              color: "rgba(68,82,121,.48)",
              fontSize: 12,
            },
          },
          axisLine: {
            lineStyle: {
              // 设置轴颜色
              color: "rgba(0,0,0,.12)",
            },
          },
          axisTick: {
            show: false,
          },
          data: xData,
        },
        yAxis: {
          type: "value",
          axisTick: {
            show: false,
          },
          // show: false,
          //网格样式
          splitLine: {
            show: true,
            lineStyle: {
              color: ["rgba(0,0,0,.04)"],
              width: 1,
              type: "solid",
            },
          },
          axisLine: {
            show: false,
            lineStyle: {
              // 设置轴颜色
              color: "rgba(0,0,0,.48)",
            },
          },
        },
        series: [
          {
            name: "收入",
            type: "bar",
            symbol: "circle",
            color: "rgba(31, 197, 87, 1)",
            data: yData1,
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2, //设置线条粗细
                },
              },
            },
          },
          {
            name: "支出",
            type: "bar",
            symbol: "circle",
            color: "rgba(243, 104, 75, 1)",
            data: yData2,
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2, //设置线条粗细
                },
              },
            },
          },
        ],
      };
      chart.setOption(option);
      const resize = window.addEventListener("resize", () => {
        this.$nextTick(() => {
          setTimeout(() => {
            chart.resize();
          }, 500);
        });
      });
      this.$once("hook:beforeDestroy", () => {
        window.removeEventListener("resize", resize);
      });
    },
    drawBar() {
      this.screenMonthProfit();
      this.screenYearProfit();
    },
    screenMonthProfit(deptId = this.deptId) {
      request({
        url: "/system/screen/monthProfit",
        method: "post",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        data: Qs.stringify({
          deptId,
          year: this.year,
        }),
      }).then((res) => {
        const x = [];
        const y = [];
        for (const i in res.data) {
          x.push(`${i}月`);
          y.push((res.data[i] / 10000).toFixed(2) || 0);
        }
        this.drawProfit("1", x, y);
      });
    },
    screenYearProfit(deptId = this.deptId) {
      request({
        url: "/system/screen/yearProfit",
        method: "post",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        data: Qs.stringify({
          deptId,
          year: this.year,
        }),
      }).then((res) => {
        const x = [];
        const y = [];
        for (const i in res.data) {
          x.push(`${i}`);
          y.push((res.data[i] / 10000).toFixed(2) || 0);
        }
        this.drawProfit("2", x, y);
      });
    },
    drawProfit(type = "1", xData, yData) {
      // 利润
      console.log(this.configurationInformation);
      const barwidth = "24";
      this.configurationInformation.profit = {
        ...this.configurationInformation.profit,
        barwidth,
        xData,
        yData,
      };
      console.log(this.configurationInformation.profit);
      this.$refs.profit.draw(this.configurationInformation.profit);
    },
    draw() {
      this.$nextTick(() => {
        // this.drawProfit("1");
        // this.drawProfit("2");
        this.screenAdvanceMonth();
        this.screenAdvanceMonthAdvanceYear();
      });
    },
    screenAdvanceMonth(deptId = this.deptId, type) {
      request({
        url: "/system/screen/AdvanceMonth",
        method: "post",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        data: Qs.stringify({
          deptId,
          year: this.year,
        }),
      }).then((res) => {
        let advanceMonthList = [];
        if (res.data && res.data.length > 0) {
          this.monthList.forEach((item, i) => {
            advanceMonthList.push({
              amount: 0,
              deptName: null,
              month: item,
              year: null,
            });
            res.data.forEach((el) => {
              if (item === el.month) {
                advanceMonthList[i] = el;
              }
            });
          });

          advanceMonthList = advanceMonthList.map(
            (item) => item.amount / 10000 || 0
          );
        }
        let xData = [];
        for (let i = 0; i < 12; i++) {
          xData.push(`${i + 1}月`);
        }
        this.drawProfit("1", xData, advanceMonthList);
      });
    },
    screenAdvanceMonthAdvanceYear(deptId = this.deptId, type) {
      request({
        url: "/system/screen/AdvanceYear",
        method: "post",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        data: Qs.stringify({
          deptId,
        }),
      }).then((res) => {
        let x = [];
        let y = [];
        let keys = Object.keys(res.data);
        if (keys.length > 0) {
          keys = keys.sort();
          keys.forEach((item) => {
            x.push(item);
            y.push((res.data[item] / 10000).toFixed(2) || 0);
          });
        }
        this.drawProfit("2", x, y);
      });
    },
    drawProfit(type = "1", x, y) {
      //利润
      console.log(configurationInformation);
      let configurationInformation = this.configurationInformation;
      let xData = [];
      let yData = [];
      let barwidth = "24";
      if (type === "1") {
        //年度

        barwidth = "16";
        configurationInformation.colors.default = "#F3684B";
      } else {
        //累计
        configurationInformation.colors.default = "#3EC4D9";
      }
      configurationInformation.profit = {
        ...configurationInformation,
        barwidth,
        xData: x,
        yData: y,
      };
      if (type === "1") {
        this.$refs.reference3.draw(configurationInformation.profit);
      } else {
        this.$refs.reference4.draw(configurationInformation.profit);
      }
    },
    open(flag) {
      // this.flag = flag;
      // // flag 1 利润 2垫资情况
      // const maps={
      //   1:"利润",
      //   2:"垫资情况",
      // }
      // this.title=maps[flag]
      this.visibility = true;
      // if (flag === 1) {
      //   this.drawBar();
      // } else {
      //   this.draw();
      // }
      this.getData1();
      this.getData2();
    },
  },
};
</script>

<style scoped lang="scss">
@import "../style/popup";

.chart {
  width: 100%;
  height: 100%;
}
</style>
